package cn.iocoder.ny.module.mall.annotation;

import cn.iocoder.ny.module.mall.config.MallProperties;
import cn.iocoder.ny.module.mall.utils.EncryptionConstants;
import cn.iocoder.ny.module.mall.utils.EncryptionUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@ControllerAdvice
public class EncryptResponse implements ResponseBodyAdvice<Object> {

    private ObjectMapper om = new ObjectMapper();



    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.hasMethodAnnotation(Encrypt.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (!MallProperties.ENCRYPTED){
            // 获取加密密钥
            byte[] keyBytes = EncryptionConstants.MALL.getBytes();
            try {
                //对整个body进行加密
                body= EncryptionUtil.encryptWithAES(om.writeValueAsBytes(body), keyBytes);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return body;
    }

    // 这里可以改造成对整个响应体都进行加密吗？ 而不是只对其中的某些变量进行加密
    public HashMap<String, Object> beforeBodyWrite(HashMap<String, Object> body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 获取加密密钥
        byte[] keyBytes = EncryptionConstants.MALL.getBytes();
        try {
            //对整个body进行加密
            body.put("data", EncryptionUtil.encryptWithAES(om.writeValueAsBytes(body.get("data")), keyBytes));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }
}